package com.android.basewars;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class ItemOverlay extends ItemizedOverlay {
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	Context mContext;
	int itemIndex;
	Button addBase;
	TextView text;
	JSONArray r;
	String userID;
	
	String gpsLat;
	String gpsLon;
	
	int[] help;
	
	public void addOverlay(OverlayItem overlay, JSONArray re, String id, int[] h) {
	    mOverlays.add(overlay);
	    r = re;
	    userID = id;
	    help = h;
	    populate();
	}
	public void addOverlay(OverlayItem overlay, String lat, String lon) {
	    mOverlays.add(overlay);
	    gpsLat = lat;
	    gpsLon = lon;
	    populate();
	}
	public void addOverlay(OverlayItem overlay,JSONArray re, String id, int[] h, String lat, String lon) {
	    mOverlays.add(overlay);
	    r = re;
	    userID = id;
	    help = h;
	    gpsLat = lat;
	    gpsLon = lon;
	    populate();
	}
	
	 public ItemOverlay(Drawable defaultMarker) {
	        super(boundCenterBottom(defaultMarker));
	        // TODO Auto-generated constructor stub
	    }

    public ItemOverlay(Drawable defaultMarker, Context context) {
        this(defaultMarker);
        mContext = context;
    }
    
    private void createBase(String user_id, String lat, String lon, String name, String desc) {
    	 InputStream is = null;
			String result = "";
			JSONObject jArray = null;
			
         HttpClient httpclient = new DefaultHttpClient();
		 HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/createbase");
	
		    try {
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		         nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
		         nameValuePairs.add(new BasicNameValuePair("lat", lat));
		         nameValuePairs.add(new BasicNameValuePair("lon", lon));
		         nameValuePairs.add(new BasicNameValuePair("basename", name));
		         nameValuePairs.add(new BasicNameValuePair("basedesc", desc));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        
		        
		        HttpEntity entity = response.getEntity();
		        is = entity.getContent();
		        
		        try{
		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		        	        StringBuilder sb = new StringBuilder();
		        	        String line = null;
		        	        while ((line = reader.readLine()) != null) {
		        	            sb.append(line + "\n");
		        	        }
		        	      is.close();
		        	        result=sb.toString();
		        	        handleMessageCreateBase(result);
		        	    }catch(Exception e){
		        	       // Log.e("log_tag", "Error converting result "+e.toString());
		        	
		        	    }


		    }catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
	}
    
    public void handleMessageCreateBase(String response) {
		try {
			
			JSONObject json_user = new JSONObject(response);
			boolean b = json_user.getBoolean("success");
			//JSONObject user = json_user.getJSONObject("result");
			if(b){
				JSONObject user = json_user.getJSONObject("result");
				String idBase = user.getString("id");
				
				updateBaseCreate(idBase);
			}
			else{
				Toast.makeText(mContext, json_user.getString("error"),
						Toast.LENGTH_SHORT).show();
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}

}
    
    private void updateBaseCreate(String idBase){
    	String upgradeType = "1";
    	
    	HttpClient httpclient = new DefaultHttpClient();
		 HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/BaseUpgrade");

		    try {
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		         nameValuePairs.add(new BasicNameValuePair("base_id", idBase));
		         nameValuePairs.add(new BasicNameValuePair("upgradetype_id", upgradeType));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        
		        Toast.makeText(mContext, "Base Aangemaakt!!!",
						Toast.LENGTH_SHORT).show();
		    }catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
    }
    
    
    private void upgradeBase(String idBase, String upgradeType, String lat, String lon) {
    	String upgradeTypeNew = "";
    	
    	if(upgradeType.equals("Basic")){
    		upgradeTypeNew = "3";
    	}else if(upgradeType.equals("First")){
    		upgradeTypeNew = "4";
    	}else if(upgradeType.equals("Second")){
    		upgradeTypeNew = "5";
    	}else if(upgradeType.equals("Third")){
    		upgradeTypeNew = "6";
    	}else if(upgradeType.equals("Fourth")){
    		upgradeTypeNew = "2";
    	}else if(upgradeType.equals("Epic")){
    		upgradeTypeNew = "2";
    	}
    	
		// TODO Auto-generated method stub
    	 HttpClient httpclient = new DefaultHttpClient();
		 HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/upgrade");
	
		 InputStream is = null;
			String result = "";
			JSONObject jArray = null;
		 
		    try {
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		         nameValuePairs.add(new BasicNameValuePair("base_id", idBase));
		         nameValuePairs.add(new BasicNameValuePair("upgradetype_id", upgradeTypeNew));
		         nameValuePairs.add(new BasicNameValuePair("lon", lon));
		         nameValuePairs.add(new BasicNameValuePair("lat", lat));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        
		        HttpEntity entity = response.getEntity();
		        is = entity.getContent();
		        
		        try{
		        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		        	        StringBuilder sb = new StringBuilder();
		        	        String line = null;
		        	        while ((line = reader.readLine()) != null) {
		        	            sb.append(line + "\n");
		        	        }
		        	      is.close();
		        	        result=sb.toString();
		        	        handleMessageLoginBaseUpgrade(result);
		        	    }catch(Exception e){
		        	       // Log.e("log_tag", "Error converting result "+e.toString());
		        	
		        	    }


		    }catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
		        
    	
	}
    
    public void handleMessageLoginBaseUpgrade(String response) {
		try {
			
			JSONObject json_user = new JSONObject(response);
			boolean b = json_user.getBoolean("success");
			//JSONObject user = json_user.getJSONObject("result");
			if(b){
				JSONObject user = json_user.getJSONObject("result");
				Toast.makeText(mContext, user.getString("Base upgraded!!!"),
						Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(mContext, json_user.getString("error"),
						Toast.LENGTH_SHORT).show();
			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}

}
    
	@Override
	protected boolean onTap(int index) {
		OverlayItem item = mOverlays.get(index);
	  
	  	itemIndex = index;
	    
	    String t = item.getTitle();
	    
	    
	    if(t.equals("GPS")){
	    	final Dialog dialog = new Dialog(mContext);
		    dialog.setContentView(R.layout.popop_icon_layout_gps_locatie);
		    dialog.setTitle(item.getTitle());
		    
		    final EditText name = (EditText)dialog.findViewById(R.id.editTextAddBaseBaseName);
		    final EditText desc = (EditText)dialog.findViewById(R.id.editTextAddBaseBaseDesc);
		    
		    final String user_id = item.getSnippet();
		    final GeoPoint p = item.getPoint();
		    
		    
		    
		    addBase = (Button) dialog.findViewById(R.id.buttonAddBase);
		    addBase.setOnClickListener(new OnClickListener() {
		        @Override
		        public void onClick(View v) {
		        	createBase(user_id,  Double.toString((double) p.getLatitudeE6() / 1.0E6) , Double.toString((double) p.getLongitudeE6() / 1.0E6), name.getText().toString(), desc.getText().toString()  );
		        	dialog.dismiss();
		        }
		    });
		    dialog.show();
	    }
	    else if(t.equals("EBASE")){
	    	final int nr = Integer.parseInt(item.getSnippet());
	    	final String idBase = item.getSnippet();
	    	getBaseName(idBase, nr);
	    }
	    else if (t.equals("OWNBASE")){
	    	final Dialog dialog = new Dialog(mContext);
	    	int nr2 = Integer.parseInt(item.getSnippet());
	    	final String idBase2 = item.getSnippet();
	 	    JSONObject base2;
	 	    String name2 = "";
	    	String decp2 = "";
	        String upgrade = "";
	 		try {
	 			
	 			base2 = r.getJSONObject( help[nr2] );
	 			name2 = base2.getString("base_name");
				decp2 = base2.getString("description"); 
				upgrade = base2.getString("upgrade_name");
			//	baseID = base2.getString("id");			
				
	 		} catch (JSONException e1) {
	 			// TODO Auto-generated catch block
	 			e1.printStackTrace();
	 		}
	 		final String upgradeNR = upgrade;
	 		
	        dialog.setContentView(R.layout.popop_icon_layout_ownbase);
			 dialog.setTitle("Own Base");
			    
		     TextView text3 = (TextView) dialog.findViewById(R.id.textViewPopUpUpgrade); 
		     text3.setText("ID: " + idBase2 + "\nName: " + name2 + "\nDesctiption: " + decp2 + "\nUpgrade name: " + upgrade );
		     Button addBase3 = (Button) dialog.findViewById(R.id.buttonAttackUpgrade);
		     addBase3.setOnClickListener(new OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	upgradeBase(idBase2, upgradeNR, gpsLat, gpsLon);
	        	dialog.dismiss();
	        }

		    });
		     dialog.show();
	    }
	
	    
	    return true;
	}
	
	
	public void attackBase(String eID) {
		final Dialog dialog = new Dialog(mContext);
		   dialog.setContentView(R.layout.popop_icon_layout_gps_locatie);
		   dialog.setTitle("Choose own base!");
		
		   ListView lv = new ListView(mContext);
		   
		   ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	        HashMap<String, String> map;
			for(int i=0;i <ownBasesresult.length();i++){
				JSONObject o;
				try {
					o = ownBasesresult.getJSONObject(i);
					
					String basename =  o.getString("name");
					map = new HashMap<String,String>();
					map.put("basename", basename);
					mylist.add(map);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 
			}


			SimpleAdapter adapterSpreekwoorden = new SimpleAdapter(mContext, mylist, R.layout.rowlistviewalfbet, new String[] {"basename"}, new int[] {R.id.rowListUsername});
			
			lv.setAdapter(adapterSpreekwoorden);
		
		final String enemyID = eID;
			
			dialog.setContentView(lv);
			lv.setOnItemClickListener(new ListView.OnItemClickListener() {
			    @Override
			    public void onItemClick(AdapterView<?> a, View v, int i, long l) {
			    	JSONObject user = null;
			    	try {
						user = ownBasesresult.getJSONObject(i);
						
						String id = user.getString("id");
		
						InputStream is = null;
						String result = "";
						JSONObject jArray = null;
					
				    	HttpClient httpclient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/battle");
			
				    try {
				    	
				        // Add your data
				        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
				         nameValuePairs.add(new BasicNameValuePair("base_attack", id));
				         nameValuePairs.add(new BasicNameValuePair("base_defend", enemyID));
				        
				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
				        // Execute HTTP Post Request
				        HttpResponse response = httpclient.execute(httppost);
				        
				        HttpEntity entity = response.getEntity();
				        is = entity.getContent();
				        
				        try{
				        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				        	        StringBuilder sb = new StringBuilder();
				        	        String line = null;
				        	        while ((line = reader.readLine()) != null) {
				        	            sb.append(line + "\n");
				        	        }
				        	      is.close();
				        	        result=sb.toString();
				        	        handleMessageAttack(result);
				        	    }catch(Exception e){
				        	       // Log.e("log_tag", "Error converting result "+e.toString());
				        	
				        	    }
	
	
				    }catch (ClientProtocolException e) {
				        // TODO Auto-generated catch block
				    } catch (IOException e) {
				        // TODO Auto-generated catch block
				    }
			    	} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}    
			    	dialog.dismiss();
				    }
				});
			dialog.show();
		}
	    
	    public void handleMessageAttack(String response) {
			try {
				
				JSONObject json_user = new JSONObject(response);
				boolean b = json_user.getBoolean("success");
				//JSONObject user = json_user.getJSONObject("result");
				if(b){
					JSONObject user = json_user.getJSONObject("result");
					String won = user.getString("won");
					if(won.equals("1")){
						Toast.makeText(mContext, "Base Attacked!!!! \n You Won!!!",
							Toast.LENGTH_SHORT).show();
					}
					else{
						Toast.makeText(mContext, "Base Attacked!!!! \n You Lost!!!",
								Toast.LENGTH_SHORT).show();
					}
				}
				else{
					Toast.makeText(mContext, json_user.getString("error"),
							Toast.LENGTH_SHORT).show();
				}
			}
			catch (JSONException e) {
				e.printStackTrace();
			}

	}
	
	@Override
	protected OverlayItem createItem(int i) {
		 return mOverlays.get(i);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}
	protected String[] ownBases;
	protected JSONArray ownBasesresult;
	protected JSONArray Baseresult;
	
	private void getOwnBases(String idB) {
		final String idBase = idB;
		
		Handler handler = new Handler() {
			
			public void handleMessage(Message message) {
				switch (message.what) {
				case HttpConnection.DID_START: {
					break;
				}
				case HttpConnection.DID_SUCCEED: {
					String response = (String) message.obj;
					try {
						JSONObject ranking = new JSONObject(response);
						boolean b = ranking.getBoolean("success");
						if(b){
							ownBasesresult = ranking.getJSONArray("result");
							
							ownBases = new String[ownBasesresult.length()];
							
							for(int i=0; i < ownBasesresult.length(); i++){
								JSONObject o;
								try {
									o = ownBasesresult.getJSONObject(i);
									
									String id =  o.getString("id");
								 	//String name = o.getString("name");
								 	//String description = o.getString("description");
								 	ownBases[i] = id;
								 	
								 	
								 	
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							
							attackBase(idBase);
						
				 		}else{
				 			//geen basissen
						}
					}
					catch (JSONException e) {
						e.printStackTrace();
					}
					break;
				}
				case HttpConnection.DID_ERROR: {
					Exception e = (Exception) message.obj;
					e.printStackTrace();
					break;
				}
				}
			}
			
		};
		new HttpConnection(handler)
			.get("http://frankkie.nl/basewars/api/v4/bases/user/"+userID);
	}




private void getBaseName(String idB, int n) {
	 final Dialog dialog = new Dialog(mContext);
	 final int nr = n;
	 JSONObject base2;
	try {
		base2 = r.getJSONObject( help[nr] );
		 String baseID = base2.getString("id");	
		
	
	final String idBase = String.valueOf( help[ nr ] );
	// Integer.parseInt(item.getSnippet());
	Handler handler = new Handler() {
		
		public void handleMessage(Message message) {
			switch (message.what) {
			case HttpConnection.DID_START: {
				break;
			}
			case HttpConnection.DID_SUCCEED: {
				String response = (String) message.obj;
				try {
					JSONObject ranking = new JSONObject(response);
					boolean b = ranking.getBoolean("success");
					if(b){
				    	
				    	JSONObject user22 = ranking.getJSONObject("result");
				 	    
				    	JSONObject base;
				 	    String name = "";
				    	String decp = "";
				    	String username = "";
				        //String baseID = "";
				 		try {
				 			base = r.getJSONObject( help[nr]  );
				 			name = base.getString("base_name");
							decp = base.getString("description"); 
							username = user22.getString("username");
							//baseID = base.getString("id");
							
				 		} catch (JSONException e1) {
				 			// TODO Auto-generated catch block
				 			e1.printStackTrace();
				 		}
				    	
				    	 dialog.setContentView(R.layout.popop_icon_layout_base);
						 dialog.setTitle("Enemy Base");
						    
					     TextView text2 = (TextView) dialog.findViewById(R.id.textViewPopUpBase); 
					     text2.setText("Username: " + username + "\nName: " + name + "\nDesctiption: " + decp );
					     Button addBase2 = (Button) dialog.findViewById(R.id.buttonAttackBase);
					     addBase2.setOnClickListener(new OnClickListener() {
				        @Override
				        public void onClick(View v) {
				        	getOwnBases(idBase);
				        	
				        	dialog.dismiss();
				        }
								
					    });
					dialog.show();
			 		}else{
			 			//geen basissen
					}
					
				}
				catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			}
			case HttpConnection.DID_ERROR: {
				Exception e = (Exception) message.obj;
				e.printStackTrace();
				break;
			}
			}
		}
		
	};
	new HttpConnection(handler)
		.get("http://frankkie.nl/basewars/api/v4/raw/SELECT%20%60username%60%20FROM%20%60User%60%20WHERE%20id%20=%20(SELECT%20%60player_id%60%20FROM%20%60Base%60%20WHERE%20id=%20'"+nr+"')");
} catch (JSONException e2) {
	// TODO Auto-generated catch block
	e2.printStackTrace();
}
}
}
